import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Text, Image } from '@tarojs/components'
import { AtCalendar, AtButton, AtFloatLayout } from 'taro-ui'
import { getAppointmentTime, getSummaryIndex } from '@/api/order/booking'
import dayjs from 'dayjs'
import { staticUrl, debounce } from '@/utils'
import { updateBooking, getOrderDetails } from '@/api/order'
import { fetchAnnualCardUse, fetchCouponView } from '@/api/annual'
import './index.scss'
import GoodList from '@/components/GoodsView/GoodList'
import MoreView from '@/components/GoodsView/MoreView'
import Iconfont from '@/components/Iconfont'
import StateList from '@/components/StateList'
const phoneIcon = staticUrl('/img/user/adviser-icon-phone.png')
const locationIcon = staticUrl('/img/user/adviser-icon-location.png')
import { hasPrevRoute } from '@/utils/global'
import { connect } from 'react-redux'

interface State {
  serverTime: any
  appointmentInfo: any
  currHour: string
  currDate: any
  validDates: any
  selectIndex?: number
  isCalendarOpened?: Boolean
  details?: any
  serverTimeLabel?: string
  selectStartAt?: any
  down?: boolean
  validDatesArr?: any
  annualDetail?: any,
  date?: any,
  selectStore: object,
	minDate:any,
	maxDate:any
}

@connect<any>(({ location }) => ({
  store: location.storeLocation
}))

export default class Index extends Component<any, State> {
  $instance = getCurrentInstance();
  protected __data__: any
  constructor (props) {
    super(props)
    this.state = {
      serverTime: null,
      appointmentInfo: null,
      currHour: '',
      currDate: 0,
      validDates: [],
      isCalendarOpened: false,
      details: {},
      serverTimeLabel: '',
      selectStartAt: 0,
      down: false,
      validDatesArr: [],
      annualDetail: {},
      date: '',
      selectStore: {},
			minDate:0,
			maxDate:0,
    }
    this.__data__ = process.env.TARO_ENV === 'weapp' ? '__data__' : 'data'
  }

  state: State

  UNSAFE_componentWillMount() { }
  async componentDidMount() {
    console.log('componentDidMount')
    const { from, applyTime, selectStore = '{}' } = this.$instance.router.params
    let storeData = JSON.parse(selectStore) || {}
    if (storeData.storeCode) { // 年卡预约进来，门店不能修改
      this.setState({
        selectStore: storeData
      })
    } else { // 通过其他方式进来的，门店不可以编辑

    }
    if (from == 'annual') {
      console.log('进来执行这里')
      await this.getAnnualCard()
      return
    }
    await this.initOrder()
    let { details } = this.state
    let locationInfo = Taro.getStorageSync('CURRENT_LOCATION_INFO') || {}
    let cityCode = locationInfo.adCode ? locationInfo.adCode : ''
    let cityName = locationInfo.name ? locationInfo.name : ''
    if (details.cityCode && details.cityCode != cityCode) {
      Taro.showModal({
        title: '温馨提示',
        content: `当前所在位置【${cityName}】距您下单门店较远如需在当地服务请重新下单。`,
        cancelText: '暂不预约',
        cancelColor: '#999999',
        confirmText: '继续预约',
        confirmColor: '#12b3ff',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            if (hasPrevRoute()) {
              Taro.navigateBack()
            } else {
              Taro.switchTab({ url: '/pages/tabbar/index/index' })
            }
          }
        }
      })
    }


  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  async componentDidShow() {
    let pages = Taro.getCurrentPages();
    let currentPage = pages[pages.length - 1]; // 获取当前页面
    if (currentPage[this.__data__].selectStore) { // 获取值
      this.setState({ selectStore: currentPage[this.__data__].selectStore, serverTime: null }, () => {
        const { applyTime }: any = this.$instance.router.params
        let params: any = {}
        if (applyTime) {
          params.date = dayjs.unix(applyTime).format('YYYY-MM-DD')
        }
        this.getSummaryIndex(params)
        this.getAppointmentTime(params)
      })
      console.log('进来的selectStore数据', currentPage[this.__data__].selectStore)
    }

  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }
  private isBooking: boolean = false
  private formData: any = {}
  //获取年卡信息
  async getAnnualCard() {
    const { formData } = this.$instance.router.params
    this.formData = JSON.parse(formData)
    Taro.showLoading({ title: '加载中' })
    try {
      let res = await fetchAnnualCardUse(formData)
      let { data } = res
      if (data.success) {
        this.setState({
          annualDetail: data.data
        }, async () => {
          for (var i = 0; i <= data.data.couponItemIds.length - 1; i++) {
            await this.fetchAnnualView(data.data.couponItemIds[i], i < data.data.couponItemIds.length - 1 ? false : true)
          }
        })
      }
    } catch (e) {
      console.log(e)
    } finally {
      Taro.hideLoading()
    }
  }
  // 获取年卡详情
  async fetchAnnualView(id, isContinue) {
    let { annualDetail } = this.state
    let res = await fetchCouponView({ id })
    console.log('endAt', res.data)
    if (!annualDetail.couponEndAt) {
      annualDetail.couponEndAt = res.data.data.endAt
    } else if (annualDetail.couponEndAt > res.data.data.endAt) {
      annualDetail.couponEndAt = res.data.data.endAt
    }
    this.setState({
      annualDetail
    }, () => {
      if (isContinue) {
        const { applyTime } = this.$instance.router.params
        let params: any = {}
        if (applyTime) {
          params.date = dayjs.unix(applyTime).format('YYYY-MM-DD')
        }
        console.log('执行到这里了吗')
        console.log('annualDetail', annualDetail)
        this.getSummaryIndex(params)
        this.getAppointmentTime(params)
      }
    })
  }
  // 获取订单详情
  async initOrder() {
    let res = await getOrderDetails({
      orderNumber: this.$instance.router.params.orderNumber
    })
    const data = res.data.data
    if (data.useCoupon.length) {
      data.useCoupon.map(v => {
        v.endAtFormat = dayjs.unix(v.endAt).format('YYYY-MM-DD HH:mm:ss')
        return v
      })
      data.useCoupon.sort(function (a, b) { return a.endAt - b.endAt });
    }
    this.setState({
      details: data,
    }, () => {
      const { applyTime }: any = this.$instance.router.params
      let params: any = {}
      if (applyTime) {
        params.date = dayjs.unix(applyTime).format('YYYY-MM-DD')
      }
      this.getSummaryIndex(params)
      this.getAppointmentTime(params)
    })
  }
  // 确定预约
  confirmBooking() {
    if (this.isBooking) return
    const { from } = this.$instance.router.params

    const { selectStartAt } = this.state
    if (!selectStartAt) return
    this.isBooking = true
    if (from === 'annual') {
      Taro.setStorageSync('BOOKING_TIME', selectStartAt)
      Taro.navigateBack({
        delta: 1
      })
      return
    }
    this.updateBooking(selectStartAt)
  }

  updateBooking(time) {
    const { selectStore, details } = this.state
    const { orderNumber } = this.$instance.router.params
    updateBooking({
      orderNumber,
      time,
      storeCode: selectStore.storeCode || details.storeCode
    }).then(res => {
      Taro.showToast({
        icon: 'none',
        title: '预约成功',
				duration: 2500,
      })
      this.isBooking = false
      this.checkedBookingNavigate()

    }).catch(e => {
      let { date } = this.state
      this.isBooking = false
      this.getAppointmentTime({
        date: date
      })
			let {data} = e.data
			e.data.data.message
			console.log('e',e)
			Taro.showToast({
        icon: 'none',
        title: `${data.message}`
      })
    })
  }

  checkedBookingNavigate() {
    Taro.navigateBack()
  }

  // 预约时间
  getAppointmentTime(params: any = {}) {
    this.setState({
      selectStartAt: 0
    })
    let { order, applyTime, from } = this.$instance.router.params
    let { details, annualDetail, selectStore } = this.state
    order = JSON.parse(order)
    const goodsData = JSON.stringify(order.map(goods => {
      const { goodsId, goodsSkuId, number, type: itemType } = goods
      return {
        goodsId,
        goodsSkuId,
        number,
        itemType
      }
    }))
    let couponEarliestEndAt = 0;
    if (from == 'annual') {
      couponEarliestEndAt = annualDetail.couponEndAt
    } else if (Object.keys(details).length && details.useCoupon.length) {
      couponEarliestEndAt = details.useCoupon[0].endAt
    }
    // if (from != 'annual') {
    params.storeCode = selectStore.storeCode || details.storeCode
    // }
    params = {
      ...params,
      goodsData,
      couponEarliestEndAt
    }
    getAppointmentTime(params).then(res => {
      const { serverTime } = this.state
      console.log('this', this)
      const data = res.data.data
      data.serviceStartAtList.forEach(e => {
        e.startAtLabel = dayjs(e.startAt * 1000).format('A')
      })
      data.serviceTimeList = [
        {
          label: '上午',
          value: data.serviceStartAtList.filter(e => e.startAtLabel == 'AM')
        },
        {
          label: '下午',
          value: data.serviceStartAtList.filter(e => e.startAtLabel == 'PM')
        }
      ]
      const size = data.serviceStartAtList.length
      let setData: any = {
        appointmentInfo: data,
        currHour: size ? data.serviceStartAtList[0].hourLabel : '',
        validDates: {
          start: dayjs(data.fromDate).valueOf(),
          end: dayjs(data.toDate).valueOf()
        }
      }
      setData.isCalendarOpened = false
      console.log('serverTime', serverTime)
      console.log('params.date', params.date)
      if (!serverTime) {
        // 微信小程序解放返回的header首字母都是大写的，支付宝都是小写的
        setData.serverTime = new Date(res.header.Date ? res.header.Date : res.header.date).getTime()
        setData.currDate = applyTime ? dayjs.unix(applyTime).valueOf() : setData.serverTime
        console.log('setData.serverTime', setData.serverTime)
        console.log('res.header.Date', res.header)
      }
      if (params.date) {
        setData.currDate = dayjs(params.date).valueOf()
      }
      let week = ['日', '一', '二', '三', '四', '五', '六']
      setData.serverTimeLabel = dayjs(setData.currDate).format('YYYY年MM月DD日 ') + ' 周' + week[new Date(setData.currDate).getDay()]
      console.log(dayjs(setData.currDate).format('YYYY年MM月DD日 '))
      console.log("setData", setData)
      this.setState(setData)
    })
  }
  //渲染日历
  getSummaryIndex(params: any = {}) {
    let { order, from } = this.$instance.router.params
    let { details, annualDetail, selectStore } = this.state
    order = JSON.parse(order)
    const goodsData = JSON.stringify(order.map(goods => {
      const { goodsId, goodsSkuId, number, type: itemType } = goods
      return {
        goodsId,
        goodsSkuId,
        number,
        itemType
      }
    }))
    let couponEarliestEndAt: any = 0;
    if (from == 'annual') {
      couponEarliestEndAt = annualDetail.couponEndAt
    } else if (Object.keys(details).length && details.useCoupon.length) {
      couponEarliestEndAt = details.useCoupon[0].endAt
    }
    params = {
      ...params,
      goodsData,
      couponEarliestEndAt: couponEarliestEndAt,
      storeCode: selectStore.storeCode || details.storeCode
    }
    console.log('params', params)
    getSummaryIndex(params).then(res => {
      let data = res.data.data
      let arr = []
      data.forEach((e, index) => {
        if (e.status == 1) {
          arr.push({ value: dayjs(e.date).format('YYYY/MM/DD') })
        }
      })
      this.setState({
				minDate:arr[0].value,
				maxDate:arr[arr.length - 1].value,
        validDatesArr: arr
      })
    })
  }
	isDuringDate =(c,b, e)=> {
		var cur = new Date(dayjs(c).format('YYYY-MM-DD 00:00:00'))
		var	begin= new Date(b)
		var	end = new Date(e)
		console.log('cur',cur)
		console.log('begin',begin)
		console.log('end',end)
		console.log('cur >= begin',cur >= begin)
		console.log('cur <= end',cur <= end)
		if (cur >= begin && cur <= end) {
				return true
		}else{
			return false
		}
	}

  // 选择日期
  changeDay = debounce((e) => {
    const { value } = e
		let {validDatesArr} = this.state
		console.log('validDatesArr',validDatesArr)
		let trueData = validDatesArr.map((item)=>{
			console.log('类型',typeof item.value)
			return String(item.value)
		})
		console.log('trueData',trueData)
		console.log('value',value)

		let selectDate = dayjs(value.start).format('YYYY/MM/DD')

		if(!trueData.includes(selectDate)){
			Taro.showToast({
				title: '当前所选日期不在可选范围之内，请重新选择！',
				icon: 'none',
				duration: 2500,
			})
			return
		}

		this.setState({
			date: value.start
		}, () => {
			this.getAppointmentTime({
				date: value.start
			})
		})
  }, 500)
  //选择具体时间
  changeSpecificTime(item) {
    let { selectStartAt } = this.state
    if (item.status != 1) return
    selectStartAt = item.startAt
    this.setState({
      selectStartAt
    })
  }
  changeGoodsStatus(e) {
    this.setState({
      down: e
    })
  }
  changeCalendarPopup(val) {
    this.setState({
      isCalendarOpened: val
    })
  }

  // 选择预约门店
  gotoSelectStores = () => {
    const { details } = this.state
    console.log('details', details)
    let cartList
    const detailsLoaded = Object.keys(details).length ? true : false
    if (detailsLoaded) {
      cartList = details.items && (Object.keys(details.items).length && details.items.goods) ? details.items.goods : null
    }
    let goodsIds = []
    console.log('cartList', cartList)
    if (cartList && cartList.length !== 0) {
      goodsIds = cartList.map(v => {
        const { id } = v
        return id
      })
    }
    console.log('goodsIds', goodsIds)
    console.log(`/pages/store/platform/index?goodsIds=${String(goodsIds)}&type=booking&orderNumber=${details.orderNumber}`)
    Taro.navigateTo({
      url: `/pages/store/platform/index?goodsIds=${String(goodsIds)}&type=booking&orderNumber=${details.orderNumber}`
    })
  }

  render() {
    const { minDate,maxDate,selectStore, currDate, appointmentInfo, validDates, isCalendarOpened, serverTimeLabel, selectStartAt, details, down, validDatesArr, annualDetail } = this.state
    const { store } = this.props
    console.log('store', store)
		console.log('validDatesArr',validDatesArr)
    let hours: any = []
    let serviceTimeList: any = []
    // let minutes = []
    if (appointmentInfo) {
      hours = appointmentInfo.serviceStartAtList
      serviceTimeList = appointmentInfo.serviceTimeList
    }
    let cartList: any = null
    let totalGoodsNumber = 0
    let { from } = this.$instance.router.params
    const detailsLoaded = Object.keys(details).length ? true : false
    if (from == 'annual' && Object.keys(annualDetail).length) {
      cartList = annualDetail.items && (Object.keys(annualDetail.items).length && annualDetail.items) ? annualDetail.items : null
    } else if (detailsLoaded) {
      cartList = details.items && (Object.keys(details.items).length && details.items.goods) ? details.items.goods : null
    }
    let annualTotalPrice: any = 0
    if (cartList) {
      cartList.forEach(gds => {
        if (from == 'annual') {


          gds.goods.goodsSkuName = gds.goods.goodsSkuFullName
        }
        totalGoodsNumber += Number(gds.number || gds.useNumber)
      })
    }
    if (!down && cartList) {
      if (cartList.length > 3) {
        cartList = cartList.slice(0, 3)
      }
    }


    return appointmentInfo && (
      <View className='booking-main'>
        <View className='top-tips'>门店每日开放部分工位线上预约,如约满,请直接前往门店排队（特殊节假日除外）;预约成功并在约定时间内到店,将优先安排服务;</View>
        {/*

			*/}
        {
          cartList && <View className='mod-goods margin-top20'>
            <View className='mod-goods-title'>服务项目</View>
            <View className='goods-item'>
              {
                cartList.map(v => {
                  let item = from == 'annual' ? v.goods : v
                  return <View key={v.id} className='li'><GoodList showRight={true} list={item} /></View>
                })
              }
              {
                from != 'annual' && details.items.goods.length > 3 && <MoreView handle={this.changeGoodsStatus.bind(this)} />
              }
            </View>
            <View className='mod-goods-bottom'>共{totalGoodsNumber}件，金额：<View className='price'>￥{details.needPayPrice || annualTotalPrice}</View></View>
          </View>
        }
        {
          from == 'annual' && store && <View className='mod-store margin-top20'>
            <View className='store-info-booking'>
              <View className='store-name'>{store.storeName}</View>
              <View className='store-address'>{store.address}</View>
            </View>
            <View className='icon'>
              <Image src={phoneIcon} className="icon-tel" onClick={() => Taro.makePhoneCall({ phoneNumber: store.phone })}></Image>
              <Image onClick={() => {
                const { latitude, longitude, address, storeName } = store
                Taro.openLocation({
                  latitude: Number(latitude),
                  longitude: Number(longitude),
                  scale: 18,
                  name: storeName,
                  address
                })
              }} src={locationIcon} className="icon-address"></Image>
            </View>
          </View>
        }

        {
          // from != 'annual' && details && <View className='mod-store margin-top20'>
          //   <View className='store-info-booking'>
          //     <View className='store-name'>{details.storeName}</View>
          //     <View className='store-address'>{details.store.address}</View>
          //   </View>
          //   <View className='icon'>
          //     <Image src={phoneIcon} className="icon-tel" onClick={() => Taro.makePhoneCall({ phoneNumber: details.store.phone })}></Image>
          //     <Image onClick={() => {
          //       const { latitude, longitude, address, storeName } = details.store
          //       Taro.openLocation({
          //         latitude: Number(latitude),
          //         longitude: Number(longitude),
          //         scale: 18,
          //         name: storeName,
          //         address
          //       })
          //     }} src={locationIcon} className="icon-address"></Image>
          //   </View>
          // </View>
        }
        {
          from != 'annual' && details ?
            // <StateList handle={this.gotoSelectStores.bind(this)} name='预约门店' context={ selectStore.storeName || details.storeName } contextIcon='icon-shaixuanxialajiantou'/>
            <StateList name='预约门店' context={selectStore.storeName || details.storeName} />
            :
            <StateList name='预约门店' context={selectStore.storeName || details.storeName} />
        }




        <View className='booking-main-view'>
          <View className='picker-time'>
            <View className='title'>选择到店时间 <Text className='tips-time'>预计施工时长：{appointmentInfo.orderConsume}分钟</Text></View>
            <View className='mod-time'>
              <View className='label'>预约时间</View>
              <View className='value' onClick={this.changeCalendarPopup.bind(this, true)}>
                {serverTimeLabel}<Iconfont size='26' color='#ccc' name='icon-shaixuanxialajiantou' />
              </View>
            </View>
            <View className='server-time'>
              <View className='server-time-mod'>
                {
                  serviceTimeList && serviceTimeList.map((v, idx) => {
                    return (
                      <View>
                        <View key={idx} className='server-time-mod-title'>{v.label}</View>
                        <View className='server-time-mod-list'>
                          {
                            v.value && v.value.length && v.value.map((item, itemIdx) => {
                              return (
                                <View key={itemIdx} className={`mod-list-item ${item.status == 3 ? 'disabled' : ''} ${item.startAt == selectStartAt ? 'active' : ''}`} onClick={this.changeSpecificTime.bind(this, item)}>
                                  <View className='right-list-item-title'>{item.timeLabel}</View>
                                </View>
                              )
                            })
                          }
                        </View>
                      </View>
                    )
                  })
                }
              </View>
            </View>
          </View>
        </View>
        {
          hours.length && <View className='confirm-btn'><AtButton onClick={this.confirmBooking.bind(this)} type='primary'>确认预约</AtButton></View>
        }
        <AtFloatLayout isOpened={isCalendarOpened} className='at-float'>
          <View className='calendar'>
            <View className='popup-title'>
              <View className='left' onClick={this.changeCalendarPopup.bind(this, false)}>取消</View>
              <View className='center'>预约时间</View>
              <View className='right'></View>
            </View>
						{/* minDate={validDatesArr[0].value} maxDate={validDatesArr[validDatesArr.length-1].value}  */}
            <AtCalendar currentDate={currDate}  onSelectDate={(e) => this.changeDay(e)} validDates={validDatesArr} />
          </View>
        </AtFloatLayout>
      </View >
    )
  }
}
